import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_page/home_business/widget/collect_status_wrapper.dart';
import 'package:xvideos/hj_page/mine_business/collec_history_buy/col_his_buy_sub_page.dart';
import 'package:xvideos/hj_page/short_video/view/right_menu/video_load_button.dart';
import 'package:xvideos/hj_utils/api_service/common_service.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:video_player/video_player.dart';

import '../../../../alert_business/video/share_video_dialog.dart';
import '../../../../hj_utils/api_service/mine_service.dart';
import '../../../../hj_utils/global.dart';
import '../../../../tools_base/debug_log.dart';
import '../../../../tools_base/global_store/store.dart';
import '../../../../tools_base/widget/net_image_widget.dart';
import '../../../user_center_page/user_center_page.dart';
import '../../../comment/comment_alert.dart';
import '../short_video_menu.dart';

class ShortRightMenu extends StatefulWidget {
  final VideoModel? videoModel;
  final VideoPlayerController? controller;

  const ShortRightMenu({super.key, this.videoModel, this.controller});

  @override
  State<StatefulWidget> createState() {
    return _ShortRightMenuState();
  }
}

class _ShortRightMenuState extends State<ShortRightMenu> {
  bool _isFollowLoading = false;
  bool _isCollectLoading = false;

  bool get isFollow => widget.videoModel?.publisher?.hasFollowed ?? false;

  bool get isMy => globalStore.isMe(widget.videoModel?.publisher?.uid);

  bool get isCollect => widget.videoModel?.vidStatus?.hasCollected ?? false;

  bool get isLike => widget.videoModel?.vidStatus?.hasLiked ?? false;

  int get collectCount => widget.videoModel?.collectCount ?? 0;

  int get likeCount => widget.videoModel?.likeCount ?? 0;

  int get itemGap => 6;

  void _onCollectEvent() async {
    try {
      bool preCollect = isCollect;
      if (_isCollectLoading) return;
      _isCollectLoading = true;

      await MineService.postCollect(widget.videoModel?.id, "SHORT", !isCollect);

      if (!preCollect) {
        widget.videoModel?.collectCount = (widget.videoModel?.collectCount ?? 0) + 1;
      } else {
        widget.videoModel?.collectCount = (widget.videoModel?.collectCount ?? 1) - 1;
      }
      _isCollectLoading = false;
      widget.videoModel?.vidStatus?.hasCollected = !isCollect;
      if (!preCollect) {
        showToast("收藏成功");
      }
      setState(() {});
    } catch (e) {
      _isCollectLoading = false;
    }
  }

  void _onLikeEvent() async {
    try {
      bool preLike = isLike;
      if (_isFollowLoading) return;
      _isFollowLoading = true;

      if (!preLike) {
        await CommonService.sendLike(widget.videoModel?.id, "SHORT");
        showToast("已点赞");
      } else {
        await CommonService.cancelLike(widget.videoModel?.id, "SHORT");
      }
      if (!preLike) {
        widget.videoModel?.likeCount = (widget.videoModel?.likeCount ?? 0) + 1;
      } else {
        widget.videoModel?.likeCount = (widget.videoModel?.likeCount ?? 1) - 1;
      }
      _isFollowLoading = false;
      widget.videoModel?.vidStatus?.hasLiked = !preLike;
      setState(() {});
    } catch (e) {
      // showToast( e.toString());
      _isFollowLoading = false;
    }
  }

  void onShowCommentSheet() async {
    widget.controller?.pause();
    await showCommentDialog(
      widget.videoModel?.id ?? '',
      objType: 'video',
      commentCount: widget.videoModel?.commentCount,
    );
  }

  void onShareEvent() async {
    widget.controller?.pause();
    Get.dialog(ShareVideoDialog(
      videoModel: widget.videoModel,
      isCoverV: true,
    ));
  }

  void _onFollowEvent() async {
    if (isMy) {
      showToast("自己不能关注自己");
      return;
    }
    if (_isFollowLoading) return;
    _isFollowLoading = true;
    setState(() {});
    int? followUID = widget.videoModel?.publisher?.uid;
    try {
      bool followStatus = !isFollow;
      await MineService.getFollow(followUID ?? 0, followStatus);
      widget.videoModel?.publisher?.hasFollowed = followStatus;
      showToast(followStatus ? "关注成功" : "已取消关注");
    } catch (e) {
      debugLog('getFollow', e.toString());
    }
    _isFollowLoading = false;
    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        if (ShortVideoMenu.isShow) ...[
          Stack(
            alignment: Alignment.bottomCenter,
            children: [
              InkWell(
                onTap: () =>
                    Get.toNamed(UserCenterPage.routeName, arguments: {'uid': widget.videoModel?.publisher?.uid ?? 0}),
                child: Padding(
                  padding: EdgeInsets.only(bottom: 8),
                  child: NetworkImageLoader(
                    imageUrl: widget.videoModel?.publisher?.portrait ?? '',
                    width: 46,
                    height: 46,
                    borderRadius: 30,
                  ),
                ),
              ),
              InkWell(
                onTap: () {
                  _onFollowEvent();
                },
                child: CollectStatusWrapper(
                  videoModel: widget.videoModel,
                  builder: () {
                    if (isFollow) {
                      return SizedBox(height: 16);
                      // return Image.asset(
                      //   'followed_red.webp'.videoPath,
                      //   width: 16,
                      //   height: 16,
                      // );
                    } else {
                      return Image.asset(
                        'add_red.webp'.videoPath,
                        width: 16,
                        height: 16,
                      );
                    }
                  },
                ),
              ),
            ],
          ),
          itemGap.sizeBoxH,
          _buildItem(
            likeCount.humanizeFormat,
            isLike ? 'like_red.png'.commonImgPath : 'like_white.png'.commonImgPath,
            onTap: _onLikeEvent,
            isSelected: isLike,
          ),
          itemGap.sizeBoxH,
          _buildItem(
            isCollect ? "已收藏" : "收藏",
            isCollect ? 'collect_red.png'.commonImgPath : 'collect_white.png'.commonImgPath,
            onTap: _onCollectEvent,
            isSelected: isCollect,
          ),
          itemGap.sizeBoxH,
          _buildItem(
            widget.videoModel?.commentCount.humanizeFormatDefault("评论") ?? "评论",
            'comment.png'.videoPath,
            onTap: onShowCommentSheet,
          ),
          itemGap.sizeBoxH,
          _buildItem(
            '分享',
            'share_arrow.png'.videoPath,
            onTap: onShareEvent,
          ),
          itemGap.sizeBoxH,
          VideoLoadButton(videoModel: widget.videoModel, isShort: true),
          itemGap.sizeBoxH,
          6.sizeBoxH,
          _buildItem(
            "",
            "eye_open.png".videoPath,
            onTap: () {
              ShortVideoMenu.isShow = !ShortVideoMenu.isShow;
              ShortVideoMenu.notifyListeners();
              setState(() {});
            },
          ),
          itemGap.sizeBoxH,
          // ChangeLineButton(
          //   ChangeLineEntry.shortVideo,
          //   changeLineCallback: (String line) {
          //     Address.cdnAddress = line;
          //     FBroadcast.instance().broadcast(SWITCH_CDN_ADDRESS);
          //   },
          // ),
        ] else ...[
          _buildItem(
            "",
            "eye_close.png".videoPath,
            onTap: () {
              ShortVideoMenu.isShow = !ShortVideoMenu.isShow;
              ShortVideoMenu.notifyListeners();
              setState(() {});
            },
          ),
          itemGap.sizeBoxH,
        ],
      ],
    );
  }

  Widget _buildItem(String title, String imgPath, {GestureTapCallback? onTap, bool isSelected = false}) {
    return InkWell(
      onTap: onTap,
      child: Column(
        children: [
          Image.asset(
            imgPath,
            width: 30,
            height: 30,
          ),
          Text(
            title,
            style: TextStyle(
              color: Color(0xffDCDCDC),
              fontSize: 12,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }
}
